<?php
/**
 * API签名生成示例（供客户端参考）
 */

class ApiSignatureHelper
{
    /**
     * 生成API请求签名
     *"api_key":"ak_3d97ebf664db97f3023b336f5fc0ad23","secret_key":"e61b4d35cf2a29e46e08e36dd075ea585614cd91470719c4411d2b946f677e12",
     * @param string $method HTTP方法
     * @param string $path 请求路径
     * @param string $body 请求体
     * @param string $apiKey API密钥
     * @param string $secretKey 签名密钥
     * @return array 包含所有请求头的数组
     */
    public static function generateRequestHeaders(
        string $method,
        string $path,
        string $body,
        string $apiKey,
        string $secretKey
    ): array {
        $timestamp = time();
        
        // 构建待签名字符串
        $stringToSign = strtoupper($method) . "\n" . 
                       $path . "\n" . 
                       $timestamp . "\n" . 
                       $body;
        
        // 生成签名
        $signature = hash_hmac('sha256', $stringToSign, $secretKey);
        
        return [
            'Authorization' => 'ApiKey ' . $apiKey,
            'Timestamp' => $timestamp,
            'Signature' => $signature,
            'Content-Type' => 'application/json',
            'X-Request-ID' => uniqid('req_')
        ];
    }
    
    /**
     * 发送API请求示例
     *
     * @param string $url 请求URL
     * @param array $data 请求数据
     * @param string $apiKey API密钥
     * @param string $secretKey 签名密钥
     * @return array 响应结果
     */
    public static function sendApiRequest(
        string $url,
        array $data,
        string $apiKey,
        string $secretKey
    ): array {
        $method = 'POST';
        $parsedUrl = parse_url($url);
        $path = $parsedUrl['path'] ?? '/';
        $body = json_encode($data, JSON_UNESCAPED_UNICODE);
        
        // 生成请求头
        $headers = self::generateRequestHeaders($method, $path, $body, $apiKey, $secretKey);
        
        // 构建cURL请求
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTPHEADER => self::formatHeaders($headers)
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            return ['success' => false, 'error' => $error];
        }
        
        return [
            'success' => true,
            'http_code' => $httpCode,
            'response' => json_decode($response, true)
        ];
    }
    
    /**
     * 格式化请求头
     *
     * @param array $headers
     * @return array
     */
    private static function formatHeaders(array $headers): array
    {
        $formatted = [];
        foreach ($headers as $key => $value) {
            $formatted[] = $key . ': ' . $value;
        }
        return $formatted;
    }
}

// 使用示例
class ApiClientExample
{
    private $apiKey = 'ak_test_device_control_001';
    private $secretKey = 'sk_test_device_control_secret_key_001';
    private $baseUrl = 'http://your-domain.com';
    
    /**
     * 发送设备重启指令
     */
    public function sendRebootCommand()
    {
        $url = $this->baseUrl . '/api/device/command';
        
        $data = [
            'target' => [
                'type' => 'single',
                'devices' => ['863780074784151']
            ],
            'commands' => [
                [
                    'cmd_name' => 'reboot',
                    'cmd_params' => [
                        'delay' => 5
                    ]
                ]
            ],
            'options' => [
                'priority' => 'high',
                'timeout' => 30,
                'async' => true
            ],
            'metadata' => [
                'source_system' => 'management_system',
                'operator' => 'admin',
                'description' => '设备维护重启'
            ]
        ];
        
        $result = ApiSignatureHelper::sendApiRequest(
            $url, 
            $data, 
            $this->apiKey, 
            $this->secretKey
        );
        
        return $result;
    }
    
    /**
     * 批量设备热点配置
     */
    public function batchHotspotConfig()
    {
        $url = $this->baseUrl . '/api/device/command';
        
        $data = [
            'target' => [
                'type' => 'batch',
                'devices' => ['863780074784151', '863780074784152']
            ],
            'commands' => [
                [
                    'cmd_name' => 'hotspot_modify',
                    'cmd_params' => [
                        'hotspot_name' => 'Company_WiFi',
                        'hotspot_password' => 'SecurePass123',
                        'hotspot_connected_num_max' => 20,
                        'hotspot_whether_hide' => 0,
                        'hotspot_band' => 1
                    ]
                ]
            ],
            'metadata' => [
                'source_system' => 'config_management',
                'operator' => 'system_admin',
                'description' => '批量更新热点配置'
            ]
        ];
        
        return ApiSignatureHelper::sendApiRequest(
            $url, 
            $data, 
            $this->apiKey, 
            $this->secretKey
        );
    }
}

// 测试代码
if (php_sapi_name() === 'cli') {
    echo "=== API签名生成示例 ===\n";
    
    $method = 'POST';
    $path = '/api/device/command';
    $body = '{"target":{"type":"single","devices":["863780074784151"]},"commands":[{"cmd_name":"reboot"}]}';
    $apiKey = 'ak_test_device_control_001';
    $secretKey = 'sk_test_device_control_secret_key_001';
    
    $headers = ApiSignatureHelper::generateRequestHeaders($method, $path, $body, $apiKey, $secretKey);
    
    echo "请求头:\n";
    foreach ($headers as $key => $value) {
        echo "{$key}: {$value}\n";
    }
    
    echo "\n=== cURL命令示例 ===\n";
    echo "curl -X POST 'http://your-domain.com/api/device/command' \\\n";
    foreach ($headers as $key => $value) {
        echo "  -H '{$key}: {$value}' \\\n";
    }
    echo "  -d '{$body}'\n";
}
?>
